package com.lhkj.ct.meta.modules.gauge.service;

import com.lhkj.ct.base.constants.ConfigConstants;
import com.lhkj.ct.base.constants.Constants;
import com.lhkj.ct.base.exception.SystemException;
import com.lhkj.ct.meta.admin.service.SysConfigService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.net.URLEncoder;
import java.util.Map;

/**
  * <p>
  *     描述：二维码
  * </p>
  */
@Validated
@Service
public class QrCodeService {

    private final Logger log = LoggerFactory.getLogger(QrCodeService.class);

    @Resource
    private SysConfigService sysConfigService;

    private final static String scope = "snsapi_userinfo";

    /**
     * TODO 微信公众号授权后跳转
     *
     * @param redirectUrl   跳转的路径
     *
     * @param params        路径上的参数可以为空，不能为null
     *
     * @return              返回二维码路径
     */
    public String generateQrCode(@NotBlank(message = "跳转路径不能为空") String redirectUrl, @NotNull(message = "参数不能为NULL") Map<String, Object> params){
        try {
            // 获取appId
            String appId = sysConfigService.selectConfigByKey(ConfigConstants.SYS_WECHAT_APPID);
            if (appId.isEmpty()) {
                throw new SystemException("系统未配置默认公众号参数，请先前往参数配置进行配置");
            }
            // 构造跳转路径
            UriComponentsBuilder redirectBuilder = UriComponentsBuilder.fromUriString(Constants.SERVICE_BASE_URL + redirectUrl);
            if (MapUtils.isNotEmpty(params)) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    redirectBuilder.queryParam(entry.getKey(), entry.getValue());
                }
            }
            String redirectUri = redirectBuilder.build().toUriString();
            log.info("二维码跳转路径 ==> {}", redirectUri);
            // 二维码地址
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://open.weixin.qq.com/connect/oauth2/authorize")
                    .queryParam("appid", appId)
                    .queryParam("redirect_uri", URLEncoder.encode(redirectUri))
                    .queryParam("response_type", "code")
                    .queryParam("scope", scope)
                    .fragment("wechat_redirect");
            // 返回二维码url
            return builder.build().toUriString();
        } catch (Exception ex) {
            log.error("二维码生成失败 ==> 路径：{},原因：{}",redirectUrl,ex.getMessage());
            throw new SystemException("二维码生成失败");
        }
    }

}
